package com.droidblackbox.manager;

import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.PowerManager;
import android.provider.Settings;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.droidblackbox.R;

public final class SystemManager {

	private static SystemManager instance = null;

	private TelephonyManager telephonyManager = null;

	private Toast toast = null;
	private ContentResolver contentResolver = null;
	private int preTimeOutValue = -2;

	private PowerManager.WakeLock wakeLock = null;

	private boolean isGps = false;
	private boolean isInternet = false;

	public synchronized static SystemManager getInstance() {
		if (instance == null) {
			synchronized (SystemManager.class) {
				if (instance == null) {
					instance = new SystemManager();
				}
			}
		}
		return instance;
	}

	private SystemManager() {

	}

	public void onPowerMode(Activity activity) {
		powerMode(activity, true);
	}

	public void offPowerMode(Activity activity) {
		powerMode(activity, false);
	}

	/**
	 * Power Mode
	 */
	private void powerMode(Activity activity, boolean isPower) {
		PowerManager powerManager = (PowerManager) activity
				.getSystemService(Context.POWER_SERVICE);
		wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK,
				"DroidBlackBox");

		if (isPower)
			wakeLock.acquire();
		else if (!isPower)
			if (wakeLock.isHeld())
				wakeLock.release();
	}

	/**
	 * 
	 * @param activity
	 * @param value
	 */

	public void setScreenOffTimeOut(Activity activity, int value) {
		screenOffTimeOut(activity, value);
	}

	private void screenOffTimeOut(Activity activity, int value) {
		contentResolver = activity.getContentResolver();
		preTimeOutValue = Settings.System.getInt(contentResolver,
				Settings.System.SCREEN_OFF_TIMEOUT, value);

		Settings.System.putInt(contentResolver,
				Settings.System.SCREEN_OFF_TIMEOUT, value);

	}

	/**
	 * Android Brightness Setting
	 * 
	 * @param activity
	 * @param value
	 *            -1.0f : Default float 0 ~ 1
	 */

	public void setScreenBrightness(Activity activity, float value) {
		screenBrightness(activity, value);
	}

	private void screenBrightness(Activity activity, float value) {
		Window window = activity.getWindow();
		WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
		lp.screenBrightness = value;
		window.setAttributes(lp);

	}

	public int getScreenOffTimeOut() {
		return preTimeOutValue;
	}

	public boolean isGps() {
		return isGps;
	}

	public boolean isGps(Activity activity) {
		gpsState(activity);
		return isGps();
	}

	private void gpsState(Activity activity) {
		String gs = Settings.Secure.getString(activity.getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

		if (gs.indexOf("gps", 0) > 0)
			isGps = true;
		else
			isGps = false;

	}

	public synchronized void setGps(boolean isGps) {
		this.isGps = isGps;
	}

	public void isGpsServiceSetting(Activity activity) {
		gpsServiceSetting(activity);
	}

	private void gpsServiceSetting(final Activity activity) {
		String gs = Settings.Secure.getString(activity.getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

		if (gs.indexOf("gps", 0) > 0) {
			isGps = true;
		} else {
			AlertDialog.Builder gsDialog = new AlertDialog.Builder(activity);
			gsDialog.setTitle("GPS Status OFF !!!");
			gsDialog.setMessage("Change Setting !!");
			gsDialog.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(
									Settings.ACTION_LOCATION_SOURCE_SETTINGS);
							intent.addCategory(Intent.CATEGORY_DEFAULT);
							activity.startActivity(intent);
						}
					}).create().show();
			isGps = false;
		}
	}

	public boolean isInternet() {
		return isInternet;
	}

	public boolean isInternet(Activity activity) {
		internetState(activity);
		return isInternet();
	}

	public synchronized void setInternet(boolean isInternet) {
		this.isInternet = isInternet;
	}

	private void internetState(Activity activity) {
		ConnectivityManager connectivityManager = (ConnectivityManager) activity
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo wifi = connectivityManager
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

		NetworkInfo mobile = connectivityManager
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

		NetworkInfo wibro = connectivityManager
				.getNetworkInfo(ConnectivityManager.TYPE_WIMAX);

		if (wifi.isConnected() || mobile.isConnected() || wibro.isConnected()) {
			isInternet = true;
		} else {
			isInternet = false;
		}
	}

	/**
	 * 
	 * @param activity
	 *            Activity class
	 */
	public void onActivityNoTitle(Activity activity) {
		activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
	}

	/**
	 * 
	 * @param activity
	 *            Activity class
	 */
	public void onActivityFullScreen(Activity activity) {
		onActivityNoTitle(activity);
		activity.getWindow().setFlags(
				WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
	}

	public void showToast(Context context, String msg) {
		toast(context, msg);
	}

	private void toast(Context context, String msg) {
		if (toast == null) {
			toast = Toast.makeText(context, "", Toast.LENGTH_LONG);
		} else {
			toast.cancel();
		}
		toast.setText(msg);
		toast.setDuration(Toast.LENGTH_LONG);
		toast.show();
	}

	public void initTitleBar(final Activity activity) {
		ImageView titleImageView = (ImageView) activity
				.findViewById(R.id.titleView);
		ImageView backImageView = (ImageView) activity
				.findViewById(R.id.backView);

		titleImageView.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub

			}
		});

		backImageView.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				activity.finish();

			}
		});

	}

	public StringBuffer getNowTime() {
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH) + 1;
		int day = calendar.get(Calendar.DAY_OF_MONTH);

		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		int minute = calendar.get(Calendar.MINUTE);
		int second = calendar.get(Calendar.SECOND);

		StringBuffer sb = new StringBuffer();

		sb.append(year).append(".");
		sb.append(month).append(".");
		sb.append(day).append("-");
		sb.append(hour).append("h.");
		sb.append(minute).append("m.");
		sb.append(second).append("s");

		return sb;
	}

	public String getNoWTimeString() {
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH) + 1;
		int day = calendar.get(Calendar.DAY_OF_MONTH);

		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		int minute = calendar.get(Calendar.MINUTE);
		int second = calendar.get(Calendar.SECOND);

		StringBuffer sb = new StringBuffer();

		sb.append(year).append(".");
		sb.append(month).append(".");
		sb.append(day).append("-");
		sb.append(hour).append("h.");
		sb.append(minute).append("m.");
		sb.append(second).append("s");

		return sb.toString();
	}

	public void onTelephony(Activity activity) {
		setTelephony(activity, true);
	}

	public void offTelephony(Activity activity) {
		setTelephony(activity, false);
	}

	public void setTelephony(final Activity activity, boolean isOnOff) {

		telephonyManager = (TelephonyManager) activity
				.getSystemService(Context.TELEPHONY_SERVICE);
		TelephonyListener telephonyListener = new TelephonyListener(activity);
		if (isOnOff) {
			telephonyManager.listen(telephonyListener,
					PhoneStateListener.LISTEN_CALL_STATE);
		} else {
			telephonyManager.listen(telephonyListener,
					PhoneStateListener.LISTEN_NONE);
		}
	}

	class TelephonyListener extends PhoneStateListener {
		private Activity activity;

		public TelephonyListener(Activity activity) {
			this.activity = activity;
		}

		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			if (state == TelephonyManager.CALL_STATE_RINGING) {
				ActivityManager activityManager = (ActivityManager) activity
						.getSystemService(Context.ACTIVITY_SERVICE);
				List<RunningAppProcessInfo> list = activityManager
						.getRunningAppProcesses();
				switch (state) {
				case TelephonyManager.CALL_STATE_IDLE:
					break;
				case TelephonyManager.CALL_STATE_RINGING:
					for (RunningAppProcessInfo i : list) {
						if (i.processName.equals("com.android.phone")) {
							activityManager.restartPackage("com.android.phone");

							StringBuffer sb = getInstance().getNowTime();
							sb.append("       ");
							sb.append(incomingNumber);
							sb.append("incoming");

							FileManager.writeLog(sb);

							// System.out.println(incomingNumber);
							// SmsManager smsManager = SmsManager.getDefault();
							// smsManager.sendTextMessage(incomingNumber, null,
							// smsManager.sendTextMessage("01033708753", null,
							// + incomingNumber + "message", null, null);
						}
					}
					break;
				case TelephonyManager.CALL_STATE_OFFHOOK:
					break;
				default:
					break;
				}

			}
		}
	}

	public String getPhoneNumber(Context context) {
		TelephonyManager telManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String phoneNum = telManager.getLine1Number();
		return phoneNum;
	}
}
